<!--
 * @Description: 选择下拉框
 * @Author: huacong
 * @Date: 2020-11-11 13:13:04
 * @LastEditTime: 2020-11-16 22:12:04
 * @LastEditors: huacong
-->
<template lang="pug">
  el-select.mr5.w(v-model="currentValue" :placeholder="`${label}`" v-on="$listeners" v-bind="formFieldProps")
    el-option(v-for="item in opts" :key="item[prop.value]" :value="item[prop.value]" :label="item[prop.label]")
</template>
<script>
import omit from 'lodash/omit'
import { dictMixin } from '@/mixins'

export default {
  name: 'ISelect',
  mixins: [dictMixin],
  props: {
    value: {
      type: [String, Number, Array, Boolean],
      default: ''
    },
    dictKey: {
      type: String,
      default: ''
    },
    label: {
      type: String,
      default: ''
    },
    options: {
      type: Array,
      default: () => ([])
    },
    props: {
      type: Object,
      default: () => ({})
    },
    dictParams: {
      type: Object,
      default: () => ({})
    }
  },
  computed: {
    prop () {
      const { props } = this
      return {
        label: props?.label || 'name',
        value: props?.value || 'id'
      }
    },
    formFieldProps () {
      return omit(this.$attrs, ['props', 'options', 'dictParams'])
    },
    currentValue: {
      // 通过计算属性，对.sync进行转换，外部也可以直接使用initId.sync
      get () {
        return this.value
      },
      set (val) {
        this.$emit('input', val)
        this.$emit('valChange', val)
      }
    },
    // 选项
    opts () {
      const { dictKey, options } = this
      return dictKey ? (this.dict[dictKey] || []) : options
    }
  },
  watch: {
    // 获取dict列表
    dictKey: {
      handler (val) {
        if (val) {
          const { dictKey, dictParams } = this
          if (!this.dict[dictKey]) {
            this.getDict({ fieldName: dictKey, ...dictParams })
          }
        }
      },
      immediate: true
    }
  }
}
</script>
